package networking.config.parser;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Config {

	private String configFileName;
	private ArrayList<Node> nodes;

	public Config(String fileName) {
		this.configFileName = fileName;
		nodes = new ArrayList<Node>();
		try {
			parseConfigFile(this.configFileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public String getConfigFileName() {
		return configFileName;
	}

	public void setConfigFileName(String configFileName) {
		this.configFileName = configFileName;
	}

	public ArrayList<Node> getNodes() {
		return nodes;
	}

	public void setNodes(ArrayList<Node> nodes) {
		this.nodes = nodes;
	}

	public void addNode(Node newNode) {
		this.nodes.add(newNode);
	}

	public Node getNode(int index) {
		return this.nodes.get(index);
	}

	public void parseConfigFile(String fileName) throws FileNotFoundException {
		try {
			BufferedReader input = new BufferedReader(new FileReader(fileName));
			String line;

			while ((line = input.readLine()) != null) {
				analyze(line);
			}
			input.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}

	@Override
	public String toString() {
		for (Node node : this.nodes) {
			node.toString();
		}
		return super.toString();
	}

	public void analyze(String line) {
		String[] elements = line.split(" ");
		if (elements[0].equals("node")) {
			Node newNode = new Node(Integer.parseInt(elements[1]), elements[2],
					Integer.parseInt(elements[3]));
			addNode(newNode);
		}

	}

}
